import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JPanel;

public class GetEmailFromWeb {

	String emailText = null;
	TextArea ta = null;
	TextField tf = null;
	Label lb = null;
	Button bt = null;
	
	public static void main(String[] args) throws IOException {
		new GetEmailFromWeb().runFrame();
	}
	
	public void runFrame() {
		new EmailFrame();
	}
	
	//在线获取网页中的内容
	void getWebFile(String u) {

			try {
				URL url = new URL(u);
				URLConnection conn = url.openConnection();

				BufferedReader is = new BufferedReader(new InputStreamReader(
						conn.getInputStream(),"utf-8"));
				String str;
				while ((str = is.readLine()) != null) {
					findAndPrint(str);
				}

				is.close();
			} catch (MalformedURLException e) {
				lb.setText("URL地址输入错误，无法解析！");
			} catch (UnsupportedEncodingException e) {
				lb.setText("未知的网页编码！");
			} catch (IOException e) {
				lb.setText("网页无法访问！");
			}

	}
	
	//解析获取的网页内容，从中取出email地址
	void findAndPrint(String line) {
		Pattern p = Pattern.compile("[\\d\\w[_]]+@[\\d\\w]+\\.[\\w]+");
		Matcher m = p.matcher(line);
		
		while(m.find()) {
			ta.append(m.group() + "\n");
		}
	}
	
	//使用图形界面呈现操作
	class EmailFrame extends Frame {

		private static final long serialVersionUID = 6422323088142691255L;
		
		//构造方法，构造窗口
		public EmailFrame() {
			setTitle("Email解析爬虫");
			setLocation(300,100);
			setSize(300,500);
			//上面板，放网址框和确定按钮
			JPanel jp = new JPanel();
			this.add(jp,BorderLayout.NORTH);
			jp.setLayout(new FlowLayout());
			//文本窗口
			ta = new TextArea();
			this.add(ta,BorderLayout.CENTER);
			//网址框
			tf = new TextField();
			tf.setColumns(30);
			jp.add(tf,BorderLayout.NORTH);
			//提示框
			lb = new Label("请在最上面的框中输入需要解析的网址",Label.CENTER);
			this.add(lb,BorderLayout.SOUTH);
			//按钮
			bt = new Button("解析");
			bt.addMouseListener(new MyMouseMonitor());
			jp.add(bt,BorderLayout.EAST);
			//关闭窗口,匿名内部类
			this.addWindowListener(new WindowAdapter() {

				@Override
				public void windowClosing(WindowEvent e) {
					System.exit(0);
				}
				
			});
			setVisible(true);
		}
	}
	
	
	//按钮事件，内部类
	class MyMouseMonitor extends MouseAdapter {

		@Override
		public void mouseClicked(MouseEvent e) {
			String url = tf.getText();
			getWebFile(url);
		}
		
	}


}
